package com.power.sifa.std.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.plf.common.utils.CommonUtils;
import com.plf.core.common.service.BaseServiceImpl;
import com.power.sifa.std.dao.Std_tartypeDao;
import com.power.sifa.std.model.Std_tartype;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import com.power.sifa.std.model.Std_admunit;
import com.power.sifa.std.dao.Std_admunitDao;
import com.power.sifa.std.service.Std_admunitService;
import com.power.sifa.std.model.pageInfo.Std_admunitPageInfo;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;

/**
 *  行政管理单位业务层实现
 */
@Service
public class Std_admunitServiceImpl extends BaseServiceImpl implements Std_admunitService {

    @Autowired
    private Std_admunitDao dao;

    @Autowired
    private Std_tartypeDao std_tartypeDao;

    @Override
    public Std_admunit getById(Serializable id) {
        return dao.findById(id).orElse(null);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveOrUpdate(Std_admunit std_admunit) {
    	// save 如果数据库不存在这条数据，就会执行保存（即将这条数据插入到数据库）；如果数据库存在这条数据，就会根据主键去更新这条数据
        if (std_admunit.getPrimaryKey() != null) {
        	 Std_admunit std_admunitfDb = dao.findById(std_admunit.getPrimaryKey()).orElse(null);
             if(std_admunitfDb != null) {
                BeanUtils.copyProperties(std_admunit, std_admunitfDb);
                dao.save(std_admunitfDb);
                return;
             }
        }
        Integer maxSort = ObjectUtil.isNotNull(this.dao.queryMaxSort()) ? this.dao.queryMaxSort() + 1: 0;
        std_admunit.setSortnum(maxSort);
        dao.save(std_admunit);
    }

    @Override
    public void removeById(Serializable id) {
        dao.deleteById(id);
    }

    @Override
    public Page<Std_admunit> findAll(Std_admunitPageInfo pageInfo) {
        //排序等定义
        Sort sort;
        if("asc".equals(pageInfo.getOrder())) {
            sort = Sort.by(Sort.Direction.ASC, pageInfo.getSort());
        }else {
            sort = Sort.by(Sort.Direction.DESC, pageInfo.getSort());
        }
        //分页的定义
        Pageable pageable = PageRequest.of(pageInfo.getPageNumber()<=1 ? 0 : pageInfo.getPageNumber()-1, pageInfo.getPageSize(), sort);
        //查询条件
        Specification spec = this.createSpecification(pageInfo);
        return dao.findAll(spec, pageable);
    }

    @Transactional(rollbackFor = Exception.class)
    public void removeByIds(List<Integer> ids) {
        dao.removeByIds(ids);
    }

    @Override
	public List<Std_admunit> findAll() {
		return dao.findAll();
	}

	@Override
	public void saveAll(List<Std_admunit> list) {
		dao.saveAll(list);
	}

    @Override
    public Std_admunit getUnitByParams(String unitName, String adid) {
        // 查询对应的业务申请id是否有对应文件类型的数据
        Specification<Std_admunit> specification = (root, query, criteriaBuilder) -> query.where(
                criteriaBuilder.and(criteriaBuilder.equal(root.get("name"), unitName), criteriaBuilder.equal(root.get(
                        "adid"), adid))
        ).getRestriction();
        List<Std_admunit> units = dao.findAll(specification);
        return CollectionUtil.isNotEmpty(units) ? units.get(0) : null;
    }

    /**
     * 通过adid来查询对应的组织机构
     * @param adids
     * @return
     */
    @Override
    public List<Std_admunit> getUnitByAdids(List<String> adids) {
        return dao.findByAdids(adids);
    }

    /**
     * 通过ids来查询对应的组织机构
     * @param ids
     * @return
     */
    public List<Std_admunit> getUnitByIds(List<String> ids) {
        return dao.findByIds(ids);
    }

    @Override
    public List<Map<String, Object>> tree() {
        List<Std_admunit> aduList = this.dao.list();
        aduList = aduList.stream().sorted(Comparator.comparing(Std_admunit::getSortnum)).collect(Collectors.toList());
        List<Std_tartype> typeList = this.std_tartypeDao.list();
        typeList = typeList.stream().sorted(Comparator.comparing(Std_tartype::getId)).collect(Collectors.toList());
        List treelist = new ArrayList(aduList.size() + typeList.size());
        treelist.addAll(aduList);
        treelist.addAll(typeList);
        treelist = JSON.parseArray(JSON.toJSONString(treelist), Map.class);
        return CommonUtils.createTree((List<Map<String, Object>>) treelist, "id", "typeid", false, null);
    }
}
